package com.lean.android.ad.core

import android.app.Activity
import android.app.Application.ActivityLifecycleCallbacks
import android.os.Bundle
import com.lean.android.ad.utils.AdLog
import com.lean.android.ad.utils.DisplayHelper

class AdAutoRelease(
    private val host: Activity,
    private val onRelease: (activity: Activity) -> Unit
) : ActivityLifecycleCallbacks {

    init {
        host.application.registerActivityLifecycleCallbacks(this)
    }

    private val adCache = hashMapOf<String, Ad>()

    fun addAd(ad: Ad) {
        AdLog.d(
            AdLog.AdAutoRelease,
            "add ad ${ad.requestId} to adCache , host ${host.javaClass.name}"
        )
        adCache[ad.requestId] = ad
    }

    fun removeAd(ad: Ad) {
        AdLog.d(AdLog.AdAutoRelease, "remove ad ${ad.requestId} , host ${host.javaClass.name}")
        adCache.remove(ad.requestId)
    }

    fun release() {
        adCache.values.forEach { ad ->
            val adView = ad.adView
            if (adView != null) {
                DisplayHelper.removeFromParent(adView)
            }
            AdLog.d(AdLog.AdAutoRelease, "release ad ${ad.requestId} , host ${host.javaClass.name}")
            ad.destroy()
        }

        adCache.clear()
        AdLog.d(AdLog.AdAutoRelease, "all ad released, unregisterActivityLifecycleCallbacks.")
        host.application.unregisterActivityLifecycleCallbacks(this)

        onRelease(host)
    }


    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {

    }

    override fun onActivityStarted(activity: Activity) {
        if (willReleaseAd(activity)) {
            AdLog.d(
                AdLog.AdAutoRelease,
                "${activity.javaClass.name} onActivityStarted called, start to release ad."
            )
            release()
        }
    }

    override fun onActivityResumed(activity: Activity) {

    }

    override fun onActivityPaused(activity: Activity) {

    }

    override fun onActivityStopped(activity: Activity) {

    }

    private fun willReleaseAd(activity: Activity): Boolean {//广告VIP
        return activity == host && AdSdk.isVip
    }

    override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
        if (willReleaseAd(activity)) {
            AdLog.d(
                AdLog.AdAutoRelease,
                "${activity.javaClass.name} onActivitySaveInstanceState called, start to release ad."
            )
            release()
        }
    }

    override fun onActivityDestroyed(activity: Activity) {
        if (willReleaseAd(activity)) {
            AdLog.d(
                AdLog.AdAutoRelease,
                "${activity.javaClass.name} onActivityDestroyed called, start to release ad."
            )
            release()
        }
    }
}